package com.project.api.sale.service;

import com.project.api.common.ApiResponse;
import com.project.api.sale.dao.OrderDao;
import com.project.api.sale.dao.OrderDetailDao;
import com.project.api.sale.common.Unit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class OrderService {
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;
    public List<OrderDetailDao> getOrderDetailByOrderId(int orderId){
        String sql = "select * from order_detail where orderId=?";
        List<OrderDetailDao> daoLists  = null;
        try {
            daoLists = mainJdbcTemplate.query(sql,new Object[] { orderId },
                    new BeanPropertyRowMapper(OrderDetailDao.class));
        } catch (EmptyResultDataAccessException e) {
            daoLists= new ArrayList();
        }
        return daoLists;
    }
    public OrderDao getOrderById(int id){
        OrderDao dao = null;
        String find = "select * from `order` where id = ?";
        try {
            dao = (OrderDao)mainJdbcTemplate.queryForObject(
                    find, new Object[] { id },new BeanPropertyRowMapper(OrderDao.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            dao=new OrderDao();
        }
        dao.setCtimeStr(formatDateStr(dao.getCreateTime()));
        List<OrderDetailDao> detailDao=getOrderDetailByOrderId(id);
        dao.setDetail(detailDao);
        return dao;
    }
    public OrderDao getOrderByNumber(String number){
        OrderDao dao = null;
        String find = "select * from `order` where number = ?";
        try {
            dao = (OrderDao)mainJdbcTemplate.queryForObject(
                    find, new Object[] { number },new BeanPropertyRowMapper(OrderDao.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            dao=new OrderDao();
        }
        int id=dao.getId();
        dao.setCtimeStr(formatDateStr(dao.getCreateTime()));
        List<OrderDetailDao> detailDao=getOrderDetailByOrderId(id);
        dao.setDetail(detailDao);
        return dao;
    }
    public List<OrderDao> getOrders(int userId,int status){
        String sql=null;
        if(status==-1){
             sql = "select * from `order` where userId=? order by createTime desc";
        }else {
             sql = "select * from `order` where userId=? and status=? order by createTime desc";
        }
        List<OrderDao> daoLists  = null;
        try {
            if(status==-1){
                daoLists = mainJdbcTemplate.query(sql,new Object[] { userId},
                        new BeanPropertyRowMapper(OrderDao.class));
            }else {
                daoLists = mainJdbcTemplate.query(sql, new Object[]{userId,status},
                        new BeanPropertyRowMapper(OrderDao.class));
            }
        } catch (EmptyResultDataAccessException e) {
            daoLists= new ArrayList();
        }
        for(int i=0;i<daoLists.size();i++){
            OrderDao orderDao=daoLists.get(i);
            int oid=orderDao.getId();
            orderDao=getOrderById(oid);
//            orderDao.setCtimeStr(formatDateStr(orderDao.getCreateTime()));
            daoLists.set(i,orderDao);
        }
        return daoLists;
    }
    @Transactional(rollbackFor=Exception.class)
    public String createOrder(OrderDao orderDao, List<OrderDetailDao> detailDaos){
            String sql = "insert into `order`(userId,`name`,phone,province,city,dist,address,total,status,description,createTime,openid,`number`) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
//        String sql = "insert into `order`(userId,`name`) values(?,?)";
        int orderId=0;
        try {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            mainJdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                    ps.setInt(1, orderDao.getUserId());ps.setString(2,orderDao.getName());
                    ps.setString(3,orderDao.getPhone());ps.setString(4,orderDao.getProvince());
                    ps.setString(5,orderDao.getCity());ps.setString(6,orderDao.getDist());
                    ps.setString(7,orderDao.getAddress());ps.setDouble(8,orderDao.getTotal());
                    ps.setInt(9,orderDao.getStatus());ps.setString(10,orderDao.getDescription());
                    ps.setLong(11,System.currentTimeMillis());ps.setString(12,orderDao.getOpenid());
                    ps.setString(13,orderDao.getNumber());
                    return ps;
                }
            }, keyHolder);
            orderId=keyHolder.getKey().intValue();
            String sql2 = "insert into order_detail(orderId,name,attribute,img,price,qty) values(?,?,?,?,?,?)";
            for(int i=0;i<detailDaos.size();i++) {
                OrderDetailDao detailDao=detailDaos.get(i);
                int count = mainJdbcTemplate.update(sql2, orderId, detailDao.getName(), detailDao.getAttribute(), detailDao.getImg(), detailDao.getPrice(), detailDao.getQty());
            }
            String sql3="delete from buycar  where userId= ?";
            int d=mainJdbcTemplate.update(sql3,orderDao.getUserId());
        } catch (Exception  e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
            return ApiResponse.Fail(e.getMessage());
        }
        return ApiResponse.Ok("插入成功",orderId);
    }
    public int updateOrder(String number,int status){
        String sql="update `order` set status= ?  where `number` = ?";
        return mainJdbcTemplate.update(sql, status,number);
    }
    public String createNumber(){
        DateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = dateFormat.format(new Date());
        return "WS"+dateStr+ Unit.getStringRandom(2);
    }
    public String formatDateStr(long time){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        long lt = new Long(s);
        Date date = new Date(time);
        res = simpleDateFormat.format(date);
        return res;
    }
}
